package kaist.sep521.lego.circlebicycle;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class SettingActivity extends Activity {
	EditText editNickname = null;
	static boolean locationSetting = MainActivity.myInfo.getShareLocation();
	static User myInfo = new User();
	public static String loginUrl = "http://14.63.196.253/~lego/login.php";

	// Alphabet + Number
	protected InputFilter filterAlphaNum = new InputFilter() {
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			Pattern ps = Pattern.compile("^[a-zA-Z0-9]+$");
			if (!ps.matcher(source).matches()) {
				return "";
			}
			return null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.permitNetwork().build());

		TextView currentNickname = (TextView) findViewById(R.id.ninkNameCurrent);
		currentNickname.setText(MainActivity.myInfo.getNickname());

		editNickname = (EditText) findViewById(R.id.editNicknameView);
		editNickname.setFilters(new InputFilter[] { filterAlphaNum });

		final Button editOK = (Button) findViewById(R.id.setting_ok);
		final Button editCancel = (Button) findViewById(R.id.setting_back);

		final ToggleButton shareLocationToggle = (ToggleButton) findViewById(R.id.shareLocationButton);
		shareLocationToggle.setChecked(MainActivity.myInfo.getShareLocation());

		// Set up the user interaction to manually show or hide the system UI.
		editOK.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if ( save() == true ) {
					onBackPressed();
				} else {
					Toast.makeText(SettingActivity.this, "save fail!!", Toast.LENGTH_SHORT).show();
				}

			}
		});

		editCancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				hideKeyboard();
				onBackPressed();
			}
		});

		// Set up the user interaction to manually show or hide the system UI.
		shareLocationToggle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (shareLocationToggle.isChecked()) {
					locationSetting = true;
				} else {
					locationSetting = false;
				}
			}
		});
	}

	private void hideKeyboard() {
		InputMethodManager inputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(editNickname.getWindowToken(),0);
	}

	private boolean save() {
		boolean changeFlag = false;
		String nickName = editNickname.getText().toString();

		if (nickName.getBytes().length > 0) {
			if (nickName.equals(MainActivity.myInfo.getNickname())) {
				Toast.makeText(SettingActivity.this,
						"Nickname is Same! ", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(SettingActivity.this,
						"Nickname is Changed! ", Toast.LENGTH_SHORT)
						.show();
				MainActivity.myInfo.setNickname(nickName);
				changeFlag = true;
			}
		} else {
			Toast.makeText(SettingActivity.this, "Enter Nickname! ",
					Toast.LENGTH_SHORT).show();
		}

		if (locationSetting != MainActivity.myInfo.getShareLocation()) {
			MainActivity.myInfo.setShareLocation(locationSetting);
			changeFlag = true;
		}

		if (changeFlag) {
			changeUserSetting();
		}

		return changeFlag;
	}

	private void changeUserSetting() {

		boolean shareflag = MainActivity.myInfo.getShareLocation();
		String changedNick = MainActivity.myInfo.getNickname();
		String user = MainActivity.myInfo.getID();

		String xml = "http://14.63.196.253/~lego/changeSetting.php?user="
				+ user + "&nick=" + changedNick + "&shareflag=" + shareflag;

		// Clear the Voice Tag on the server.
		try {

			URL url = new URL(xml);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				Log.w("USER SETTING", "HTTP_SEND_OK");

			} else {
				Toast.makeText(this, "Server connection error!!",
						Toast.LENGTH_SHORT).show();
			}
			conn.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		editNickname.setText(null);
	}

}
